import React from 'react'

/*普通拖拽组件*/
class Drag extends React.Component {
	constructor(props) {
        super(props);
        this.state = {
            x:0,
            y:0,
            lock:false,
            startX:0,
            startY:0,
            beginX:0,
            beginY:0
        }
    }
    /*鼠标按下时*/
    handleMouseDown = (e) => {
        if(!this.state.lock) {
            this.setState({
                lock:true,
                startX:e.touches?e.touches[0].clientX:e.clientX,
                startY:e.touches?e.touches[0].clientY:e.clientY
            })
        }
    }
    /*鼠标移动时*/
    handleMouseMove = (e) => {
        if(this.state.lock) {//移动的是moveRef
            let moveX = e.touches?e.touches[0].clientX:e.clientX,
            moveY = e.touches?e.touches[0].clientY:e.clientY;
            this.setState( oldState => ({
                x:moveX-(oldState.startX-oldState.beginX),
                y:moveY-(oldState.startY-oldState.beginY)
            }));
        }
    }
    /*鼠标弹起时*/
    handleMouseUp = (e) => {
        if(this.state.lock) {
            this.setState( oldState => ({
                lock:false,
                beginX:oldState.x,
                beginY:oldState.y
            }));
        }
    }
    render() {
        return(
            <div onMouseDown={this.handleMouseDown} onTouchStart={this.handleMouseDown} onMouseUp={this.handleMouseUp} onTouchEnd={this.handleMouseUp} onMouseMove={this.handleMouseMove} onTouchMove={this.handleMouseMove} >
                <div style={{left:this.state.x,top:this.state.y,display:'inline-block',position:'relative'}}>
                    {this.props.children}
                </div>
            </div>
        )
    }
}
export default Drag
